package com.dcxm.stu.service.impl

import com.dcxm.stu.bean.Message
import com.dcxm.stu.bean.Student
import com.dcxm.stu.dao.impl.StudentDaoI
import com.dcxm.stu.service.StudentService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.IOException
import java.util.*

@Service
class StudentServiceI : StudentService {

    @Autowired
    private lateinit var studentDao: StudentDaoI

    /**
     * @param student student类
     * @return 是否密码正确的boolean值
     */

    override fun login(student: Student): Student {
        val studentD = studentDao.getUserInfo(student)
        if (!studentD.isFlag) {
            studentD.username = null
            studentD.password = null
            studentD.telphone = null
            studentD.message = "密码错误"
        } else {
            studentD.isFlag = true
            studentD.message = "登陆成功"
        }
        return studentD
    }

    /**
     * @param student 学生
     * @return message 返回的json串信息封装
     */
    override fun register(student: Student): Message {
        val row = studentDao.insertInfo(student, "213")
        val text: String
        val flag: Boolean
        if (row == 1) {
            text = "注册成功"
            flag = true
        } else {
            text = "电话号码已经被注册"
            flag = false
        }
        return Message(text, flag)
    }

    /**
     * @param student
     * @return message
     */
    override fun updateInfo(student: Student): Message {
        val row = studentDao.updateInfo(student)
        var text = "修改成功"
        var flag = true
        if (row != 1) {
            text = "修改失败"
            flag = false
        }
        return Message(text, flag)
    }

    /**
     * @param file 上传的文件
     * @param telphone 电话号
     * @param path 存储路径
     */
    override fun upImg(file: MultipartFile, telphone: String, path: String): Message {
        //原始名字
        val originalFilename = file.originalFilename
        //新图片名称
        val newfilename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf('.'))
        //新图片
        val newFile = File(path + newfilename)
        //写入磁盘
        try {
            file.transferTo(newFile)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        val row = studentDao.upImg(newfilename, telphone)
        var mes = path + newfilename
        var flag = true
        if (row != 1) {
            mes = "null"
            flag = false
        }
        return Message(mes, flag)
    }
}